package cn.mesmile.account.controller;

import cn.mesmile.account.entity.Account;
import cn.mesmile.account.service.AccountService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

/**
 * @author zb
 * @date 2020/12/16 18:30
 * @Description
 */
@AllArgsConstructor
@RequestMapping("/api/v1/account")
@RestController
public class AccountController {

    private final AccountService accountService;

    /**
     *  扣除余额
     * @return
     */
    @GetMapping("/deduct/{accountId}/{price}")
    public Boolean deductBalance(@PathVariable("accountId")Long accountId, @PathVariable("price")BigDecimal price) {
        double v = price.doubleValue();
        if (v < 0){
            return false;
        }
        LambdaQueryWrapper<Account> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(accountId != null, Account::getId, accountId);
        Account account = accountService.getOne(lambdaQuery);
        if (account == null){
            return false;
        }
        BigDecimal surplusMoney = account.getMoney();
        BigDecimal result = surplusMoney.subtract(price);
        // 大于的时候返回 1   等于返回 0   小于返回 -1
        if (result.compareTo(BigDecimal.ZERO) < 0){
            return false;
        }
        LambdaUpdateWrapper<Account> lambdaUpdate = Wrappers.lambdaUpdate();
        lambdaUpdate.set( Account::getMoney, result);
        lambdaUpdate.eq(accountId != null , Account::getId, accountId);
        return accountService.update(lambdaUpdate);
    }


}
